﻿#region Copyright information
// 
// Copyright © 2005-2013 Yongkee Cho. All rights reserved.
// 
// This code is a part of the Biological Object Library and governed under the terms of the
// GNU Lesser General  Public License (LGPL) version 2.1 which accompanies this distribution.
// For more information on the LGPL, please visit http://bol.codeplex.com/license.
// 
// - Filename: Manhattan.cs
// - Author: Yongkee Cho
// - Email: yongkeecho@gmail.com
// - Date Created: 2012-09-06 11:39 AM
// - Last Modified: 2013-01-25 3:59 PM
// 
#endregion
using System;
using System.Collections.Generic;
using System.Linq;

namespace BOL.Linq.Distances
{
    public static partial class Disimilarity
    {
        public static double Manhattan(this IEnumerable<bool> first, IEnumerable<bool> second)
        {
            var bc = first.BinaryCardinality(second);

            return bc.Item2 + bc.Item3;
        }

        public static double MeanManhattan(this IEnumerable<bool> first, IEnumerable<bool> second)
        {
            var bc = first.BinaryCardinality(second);
            var bc2 = bc.Item2 + bc.Item3;

            return bc2 / (double)(bc.Item1 + bc2 + bc.Item4);
        }

        public static double Vari(this IEnumerable<bool> first, IEnumerable<bool> second)
        {
            var bc = first.BinaryCardinality(second);
            var bc2 = bc.Item2 + bc.Item3;

            return 0.25 * bc2 / (bc.Item1 + bc2 + bc.Item4);
        }

        public static double SizedDifference(this IEnumerable<bool> first, IEnumerable<bool> second)
        {
            var bc = first.BinaryCardinality(second);
            var bc2 = bc.Item2 + bc.Item3;

            return bc2 * bc2 / Math.Pow(bc.Item1 + bc2 + bc.Item4, 2);
        }

        public static double ShapedDifference(this IEnumerable<bool> first, IEnumerable<bool> second)
        {
            var bc = first.BinaryCardinality(second);
            var n = bc.Item1 + bc.Item2 + bc.Item3 + bc.Item4;

            return (n * (bc.Item2 + bc.Item3) * Math.Pow(bc.Item2 - bc.Item3, 2)) / Math.Pow(n, 2);
        }

        public static double PatternDifference(this IEnumerable<bool> first, IEnumerable<bool> second)
        {
            var bc = first.BinaryCardinality(second);

            return 4.0 * bc.Item2 * bc.Item3 / Math.Pow(bc.Item1 + bc.Item2 + bc.Item3 + bc.Item4, 2);
        }

        public static double Manhattan(this IEnumerable<double> first, IEnumerable<double> second)
        {
            var x = first.ToList();
            var y = second.ToList();
            var length = Math.Min(x.Count, y.Count);

            return Math.Sqrt(x.Zip(y, (xc, yc) => Math.Abs(xc - yc)).Sum(diff => diff * diff) / length);
        }
    }
}
